<template>
  <div class="profile-settings-page">
    <van-nav-bar title="个人设置" left-arrow @click-left="goBack" fixed />

    <div class="container">
      <!-- 个人资料部分 -->
      <div class="section-card">
        <div class="section-title">个人资料</div>

        <van-cell-group>
          <van-cell title="头像" is-link center @click="uploadAvatarAction">
            <template #right-icon>
              <img class="user-avatar" :src="userInfo.avatar || 'https://randomuser.me/api/portraits/men/32.jpg'"
                alt="用户头像">
            </template>
          </van-cell>

          <!-- 昵称功能已移除 -->

          <van-cell title="个性签名" is-link @click="editField('bio')">
            <template #value>
              <div class="bio-text">{{ userInfo.bio || '未设置' }}</div>
            </template>
          </van-cell>

          <van-cell title="性别" :value="genderText" is-link @click="openGenderPicker" />

          <van-cell title="生日" :value="formattedBirthday" is-link @click="openDatePicker" />
        </van-cell-group>
      </div>

      <!-- 账户与安全部分 -->
      <div class="section-card">
        <div class="section-title">账户与安全</div>

        <div class="security-item">
          <div class="security-icon">
            <i class="fas fa-mobile-alt"></i>
          </div>
          <div class="security-info">
            <div class="security-title">手机号</div>
            <div class="security-desc">{{ maskPhone(userInfo.phone) }}</div>
          </div>
          <div class="security-action" @click="editField('phone')">修改</div>
        </div>

        <div class="security-item">
          <div class="security-icon">
            <i class="fas fa-lock"></i>
          </div>
          <div class="security-info">
            <div class="security-title">登录密码</div>
            <div class="security-desc">建议定期修改，保障账户安全</div>
          </div>
          <div class="security-action" @click="editField('password')">修改</div>
        </div>

        <div class="security-item">
          <div class="security-icon">
            <i class="fas fa-shield-alt"></i>
          </div>
          <div class="security-info">
            <div class="security-title">安全中心</div>
            <div class="security-desc">保障账户和资金安全</div>
          </div>
          <div class="security-action">
            <i class="fas fa-chevron-right setting-arrow"></i>
          </div>
        </div>
      </div>

      <!-- 生物识别设置 -->
      <div class="section-card">
        <div class="section-title">生物识别登录</div>

        <van-cell title="使用生物识别">
          <template #right-icon>
            <van-switch v-model="userSettings.useBiometric" size="24" @update:model-value="updateBiometricSettings" />
          </template>
        </van-cell>

        <div class="biometric-setup" v-if="userSettings.useBiometric">
          <div class="setup-title">选择使用的生物识别方式</div>
          <div class="biometric-options">
            <div class="biometric-option"
              :class="{ 'biometric-selected': userSettings.biometricType === 'fingerprint' }"
              @click="selectBiometricType('fingerprint')">
              <i class="fas fa-fingerprint biometric-icon"></i>
              <div class="biometric-name">指纹识别</div>
            </div>
            <div class="biometric-option" :class="{ 'biometric-selected': userSettings.biometricType === 'face' }"
              @click="selectBiometricType('face')">
              <i class="fas fa-user biometric-icon"></i>
              <div class="biometric-name">面部识别</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 通用设置部分 -->
      <div class="section-card">
        <div class="section-title">通用设置</div>

        <van-cell title="地址管理" is-link to="/address" />

        <van-cell title="消息通知">
          <template #right-icon>
            <van-switch v-model="userSettings.notifications" size="24"
              @update:model-value="updateNotificationSettings" />
          </template>
        </van-cell>

        <van-cell title="隐私设置" is-link @click="goToPrivacy" />

        <van-cell title="清除缓存" is-link @click="clearCache">
          <template #value>
            <span class="cache-size">{{ cacheSize }}</span>
          </template>
        </van-cell>
      </div>

      <!-- 退出登录按钮 -->
      <van-button class="logout-button" block type="danger" round @click="showLogoutConfirm">退出登录</van-button>

      <!-- 版本信息 -->
      <div class="version-info">
        宠物乐园 v1.0.0
      </div>
    </div>

    <!-- 底部弹出层 -->
    <van-popup v-model:show="showDatePicker" position="bottom" @closed="onPopupClosed">
      <van-date-picker title="选择生日" :min-date="minDate" :max-date="maxDate" :default-date="defaultDate"
        @confirm="onDateConfirm" @cancel="showDatePicker = false" />
    </van-popup>

    <van-popup v-model:show="showGenderPicker" position="bottom" @closed="onPopupClosed">
      <van-picker title="选择性别" :columns="genderOptions" @confirm="onGenderConfirm" @cancel="showGenderPicker = false"
        show-toolbar value-key="text" />
    </van-popup>

    <van-dialog v-model:show="showInput" :title="dialogTitle" show-cancel-button @confirm="saveField"
      @cancel="cancelInputDialog">
      <van-field v-if="currentField === 'password'" v-model="oldPasswordValue" type="password" placeholder="请输入旧密码" />
      <van-field v-model="inputValue" :type="currentField === 'password' ? 'password' : 'text'"
        :placeholder="inputPlaceholder" />
    </van-dialog>

    <!-- 头像上传和预览弹窗 -->
    <van-popup v-model:show="showAvatarPreview" position="bottom" round :style="{ height: '50%' }"
      @close="cancelAvatarUpload">
      <div class="avatar-upload-container">
        <div class="popup-header">
          <div class="popup-title">更换头像</div>
          <div class="popup-close" @click="cancelAvatarUpload">
            <i class="fas fa-times"></i>
          </div>
        </div>

        <div class="avatar-preview-area">
          <img v-if="previewImageUrl" :src="previewImageUrl" alt="头像预览" class="avatar-preview-image">
          <div v-else class="avatar-placeholder">
            <i class="fas fa-user"></i>
            <div>请选择图片</div>
          </div>
        </div>

        <div class="avatar-actions">
          <van-button type="default" block @click="uploadAvatarAction">选择图片</van-button>
          <van-button v-if="previewImageUrl" type="primary" block @click="confirmAvatarUpload">
            上传头像
          </van-button>
        </div>
      </div>
    </van-popup>

    <input ref="fileInput" type="file" accept="image/*" style="display:none" @change="onFileChange" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog, showLoadingToast, closeToast } from 'vant';
import type { PickerOption } from 'vant';
import api from '../network/api';

export default defineComponent({
  name: 'ProfileSettingsView',

  setup() {
    const router = useRouter();
    const loading = ref(false);
    const fileInput = ref<HTMLInputElement | null>(null);

    // 用户信息
    const userInfo = ref<any>({});

    // 用户设置
    const userSettings = reactive({
      useBiometric: false,
      biometricType: 'fingerprint', // 'fingerprint' or 'face'
      notifications: true,
    });

    // 缓存大小
    const cacheSize = ref('0MB');

    // 状态控制
    const showDatePicker = ref(false);
    const showGenderPicker = ref(false);
    const showInput = ref(false);
    const showAvatarPreview = ref(false);
    const previewImageUrl = ref('');
    const selectedFile = ref<File | null>(null);

    const dialogTitle = ref('');
    const inputValue = ref('');
    const oldPasswordValue = ref('');
    const inputPlaceholder = ref('');
    const currentField = ref('');

    // 日期范围
    const minDate = new Date(1950, 0, 1);
    const maxDate = new Date();
    const defaultDate = computed(() => {
      if (userInfo.value.birthday) {
        return new Date(userInfo.value.birthday);
      }
      return new Date(1990, 0, 15);
    });

    // 性别选项
    const genderOptions = [
      { text: '男', value: 'male' },
      { text: '女', value: 'female' }
    ] as PickerOption[];

    // 计算属性
    const genderText = computed(() => {
      const genderMap: { [key: string]: string } = {
        'male': '男',
        'female': '女'
      };
      return genderMap[userInfo.value.gender] || '未设置';
    });

    // 格式化生日显示为年月日格式
    const formattedBirthday = computed(() => {
      if (!userInfo.value.birthday) return '未设置';
      const parts = userInfo.value.birthday.split('-');
      if (parts.length === 3) {
        return `${parts[0]}年${parts[1]}月${parts[2]}日`;
      }
      return userInfo.value.birthday;
    });

    // 获取用户信息
    const fetchUserProfile = async () => {
      try {
        loading.value = true;
        showLoadingToast({
          message: '加载中...',
          forbidClick: true,
        });

        const response = await api.getUserProfile();
        const responseData = response as any;

        // 检查是否有有效的用户数据
        if (responseData && responseData.code === 100 && responseData.data) {
          const profile = responseData.data;
          userInfo.value = profile;

          // 加载用户设置
          userSettings.useBiometric = Boolean(profile.useBiometric);
          userSettings.biometricType = profile.biometricType || 'fingerprint';
          userSettings.notifications = profile.notificationsEnabled !== false;

          // 加载缓存大小（模拟数据）
          fetchCacheSize();
        } else {
          showToast('获取用户信息失败');
          console.error('后端返回数据格式错误或无用户数据');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        showToast('获取用户信息失败');
      } finally {
        loading.value = false;
        closeToast();
      }
    };

    // 获取缓存大小（模拟）
    const fetchCacheSize = () => {
      // 模拟获取缓存大小，实际应该是从本地存储或后端获取
      const randomSize = (Math.random() * 100).toFixed(1);
      cacheSize.value = `${randomSize}MB`;
    };

    // 方法
    const goBack = () => {
      router.back();
    };

    const maskPhone = (phone: string) => {
      if (!phone) return '';
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    };

    // 打开日期选择器
    const openDatePicker = () => {
      console.log('打开日期选择器');
      setTimeout(() => {
        showDatePicker.value = true;
        console.log('日期选择器状态:', showDatePicker.value);
      }, 0);
    };

    // 打开性别选择器
    const openGenderPicker = () => {
      console.log('打开性别选择器');
      setTimeout(() => {
        showGenderPicker.value = true;
        console.log('性别选择器状态:', showGenderPicker.value);
      }, 0);
    };

    // 弹窗关闭回调
    const onPopupClosed = () => {
      console.log('弹窗已关闭');
    };

    const cancelInputDialog = () => {
      showInput.value = false;
      inputValue.value = '';
      oldPasswordValue.value = '';
    };

    const onDateConfirm = async (value: any) => {
      console.log('日期选择器返回的值:', value);

      let newBirthday = '';

      // 检查value是否为对象且有selectedValues属性
      if (value && value.selectedValues && Array.isArray(value.selectedValues) && value.selectedValues.length >= 3) {
        // 如果是选择器返回的对象格式
        const [year, month, day] = value.selectedValues;
        newBirthday = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        console.log('从selectedValues解析的日期:', newBirthday);
      } else if (value instanceof Date) {
        // 如果是Date对象
        const year = value.getFullYear();
        const month = String(value.getMonth() + 1).padStart(2, '0');
        const day = String(value.getDate()).padStart(2, '0');
        newBirthday = `${year}-${month}-${day}`;
      } else {
        console.error('未知的日期格式:', value);
        showToast('日期格式错误');
        showDatePicker.value = false;
        return;
      }

      try {
        showLoadingToast({
          message: '更新中...',
          forbidClick: true,
        });
        userInfo.value.birthday = newBirthday;
        await api.updateUserProfile(userInfo.value);

        showToast('生日信息更新成功');
      } catch (error) {
        showToast('更新生日信息失败');
        console.error('更新生日信息失败:', error);
      } finally {
        closeToast();
        showDatePicker.value = false;
      }
    };

    const onGenderConfirm = async (value: any) => {
      // 直接获取对象的selectedValues属性
      console.log('选择的性别对象:', value);

      // 从对象结构中正确获取性别值
      let newGender = 'male';
      if (value && value.selectedValues && value.selectedValues.length > 0) {
        newGender = value.selectedValues[0];
        console.log('从selectedValues获取的性别值:', newGender);
      }

      console.log('最终性别值:', newGender);

      try {
        showLoadingToast({
          message: '更新中...',
          forbidClick: true,
        });
        userInfo.value.gender = newGender;
        await api.updateUserProfile(userInfo.value);

        showToast('性别信息更新成功');
      } catch (error) {
        showToast('更新性别信息失败');
        console.error('更新性别信息失败:', error);
      } finally {
        closeToast();
        showGenderPicker.value = false;
      }
    };

    const editField = (field: string) => {
      console.log('编辑字段:', field);
      currentField.value = field;

      switch (field) {
        // 昵称功能已移除
        case 'bio':
          dialogTitle.value = '修改个性签名';
          inputValue.value = userInfo.value.bio;
          inputPlaceholder.value = '请输入个性签名';
          break;
        case 'phone':
          dialogTitle.value = '修改手机号';
          inputValue.value = '';
          inputPlaceholder.value = '请输入新手机号';
          break;
        case 'password':
          dialogTitle.value = '修改密码';
          inputValue.value = '';
          oldPasswordValue.value = '';
          inputPlaceholder.value = '请输入新密码';
          break;
      }

      // 确保在下一个事件循环中设置弹窗状态，避免可能的响应式更新问题
      setTimeout(() => {
        showInput.value = true;
        console.log('设置对话框状态为:', showInput.value);
      }, 0);
    };

    const saveField = async () => {
      if (currentField.value === 'password') {
        if (!oldPasswordValue.value.trim()) {
          showToast('请输入旧密码');
          return;
        }
        if (!inputValue.value.trim()) {
          showToast('请输入新密码');
          return;
        }
      } else if (!inputValue.value.trim()) {
        showToast('输入不能为空');
        return;
      }

      try {
        showLoadingToast({
          message: '保存中...',
          forbidClick: true,
        });

        switch (currentField.value) {
          // 昵称功能已移除
          case 'bio':
            userInfo.value.bio = inputValue.value;
            await api.updateUserProfile(userInfo.value);
            break;
          case 'phone':
            // 简单的手机号验证
            if (!/^1[3-9]\d{9}$/.test(inputValue.value)) {
              showToast('请输入正确的手机号');
              closeToast();
              return;
            }
            userInfo.value.phone = inputValue.value;
            await api.updateUserProfile(userInfo.value);
            break;
          case 'password':
            // 这里应该调用修改密码API
            await api.updatePassword({ oldPassword: oldPasswordValue.value, password: inputValue.value });
            break;
        }

        // 保存成功提示
        showToast('保存成功');
      } catch (error) {
        showToast('保存失败');
        console.error('保存失败:', error);
      } finally {
        closeToast();
        cancelInputDialog();
      }
    };

    const uploadAvatarAction = () => {
      // 触发文件选择
      if (fileInput.value) {
        fileInput.value.click();
      }
    };

    const onFileChange = async (event: Event) => {
      const target = event.target as HTMLInputElement;
      if (target.files && target.files.length > 0) {
        const file = target.files[0];

        // 验证文件类型
        if (!file.type.includes('image/')) {
          showToast('请选择图片文件');
          return;
        }

        // 验证文件大小（限制为5MB）
        if (file.size > 5 * 1024 * 1024) {
          showToast('图片大小不能超过5MB');
          return;
        }

        // 保存选中的文件并显示预览
        selectedFile.value = file;
        previewImageUrl.value = URL.createObjectURL(file);
        showAvatarPreview.value = true;
      }
    };

    // 取消头像上传
    const cancelAvatarUpload = () => {
      showAvatarPreview.value = false;
      previewImageUrl.value = '';
      selectedFile.value = null;

      // 重置文件输入框，以便再次选择同一文件
      if (fileInput.value) {
        fileInput.value.value = '';
      }
    };

    // 确认上传头像
    const confirmAvatarUpload = async () => {
      if (!selectedFile.value) {
        showToast('请先选择图片');
        return;
      }

      try {
        showLoadingToast({
          message: '处理图片中...',
          forbidClick: true,
        });

        // 压缩图片
        const compressedFile = await compressImage(selectedFile.value);
        console.log('图片压缩结果:', compressedFile ? '压缩成功' : '压缩失败，使用原图');

        showLoadingToast({
          message: '处理中...',
          forbidClick: true,
        });

        // 使用压缩后的图片，如果压缩失败则使用原图
        const fileToUpload = compressedFile || selectedFile.value;

        // 直接将图片转换为base64
        const base64Data = await fileToBase64(fileToUpload);

        userInfo.value.avatar = base64Data;
        await api.updateUserProfile(userInfo.value);

        // 成功更新用户头像
        showToast('头像更新成功');
      } catch (error) {
        showToast('头像更新失败');
        console.error('头像更新失败:', error);
      } finally {
        closeToast();
        // 关闭预览窗口
        showAvatarPreview.value = false;
        previewImageUrl.value = '';
        selectedFile.value = null;

        // 重置文件输入框，以便再次选择同一文件
        if (fileInput.value) {
          fileInput.value.value = '';
        }
      }
    };

    // 将文件转换为base64
    const fileToBase64 = (file: File | Blob): Promise<string> => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          if (reader.result) {
            resolve(reader.result.toString());
          } else {
            reject(new Error('转换base64失败'));
          }
        };
        reader.onerror = (error) => reject(error);
        reader.readAsDataURL(file);
      });
    };

    // 压缩图片的方法
    const compressImage = (file: File): Promise<Blob | null> => {
      return new Promise((resolve) => {
        try {
          const reader = new FileReader();
          reader.onload = (e) => {
            if (!e.target || !e.target.result) {
              resolve(null);
              return;
            }

            const img = new Image();
            img.onload = () => {
              // 设置压缩尺寸
              let width = img.width;
              let height = img.height;

              // 如果图片尺寸过大，按比例缩小
              const MAX_WIDTH = 800;
              const MAX_HEIGHT = 800;

              if (width > MAX_WIDTH) {
                const ratio = MAX_WIDTH / width;
                width = MAX_WIDTH;
                height = height * ratio;
              }

              if (height > MAX_HEIGHT) {
                const ratio = MAX_HEIGHT / height;
                height = MAX_HEIGHT;
                width = width * ratio;
              }

              // 创建canvas并绘制压缩后的图片
              const canvas = document.createElement('canvas');
              canvas.width = width;
              canvas.height = height;

              const ctx = canvas.getContext('2d');
              if (!ctx) {
                resolve(null);
                return;
              }

              ctx.drawImage(img, 0, 0, width, height);

              // 转换为Blob
              canvas.toBlob((blob) => {
                resolve(blob);
              }, file.type, 0.85); // 压缩质量为85%
            };

            img.src = e.target.result as string;
          };

          reader.readAsDataURL(file);
        } catch (error) {
          console.error('图片压缩失败:', error);
          resolve(null);
        }
      });
    };

    const selectBiometricType = async (type: string) => {
      try {
        showLoadingToast({
          message: '设置中...',
          forbidClick: true,
        });

        await api.updateUserProfile({
          biometricType: type  // 改为与后端实体类字段名一致
        });

        userSettings.biometricType = type;
        userInfo.value.biometricType = type;
        showToast({
          message: '设置已更新',
          duration: 4000
        });
      } catch (error) {
        showToast({
          message: '设置更新失败',
          duration: 4000
        });
        console.error('设置更新失败:', error);
      } finally {
        closeToast();
      }
    };

    const updateBiometricSettings = async (value: boolean) => {
      try {
        showLoadingToast({
          message: '设置中...',
          forbidClick: true,
        });

        await api.updateUserProfile({
          useBiometric: value ? 1 : 0  // 改为与后端实体类字段名一致
        });

        userInfo.value.useBiometric = value ? 1 : 0;
        showToast({
          message: value ? '已开启生物识别登录' : '已关闭生物识别登录',
          duration: 4000
        });
      } catch (error) {
        // 恢复开关状态
        userSettings.useBiometric = !value;
        showToast({
          message: '设置更新失败',
          duration: 4000
        });
        console.error('设置更新失败:', error);
      } finally {
        closeToast();
      }
    };

    const updateNotificationSettings = async (value: boolean) => {
      try {
        showLoadingToast({
          message: '设置中...',
          forbidClick: true,
        });

        await api.updateUserSettings({
          notifications_enabled: value ? 1 : 0
        });

        showToast(value ? '已开启通知' : '已关闭通知');
      } catch (error) {
        // 恢复开关状态
        userSettings.notifications = !value;
        showToast('设置更新失败');
        console.error('设置更新失败:', error);
      } finally {
        closeToast();
      }
    };

    const goToPrivacy = () => {
      // 跳转到隐私设置页面
      router.push('/privacy');
    };

    const clearCache = () => {
      showDialog({
        title: '清除缓存',
        message: '确定要清除缓存吗？',
        showCancelButton: true
      })
        .then(async () => {
          // 清除缓存的逻辑
          try {
            showLoadingToast({
              message: '清除中...',
              forbidClick: true,
            });

            await api.clearUserCache();
            cacheSize.value = '0MB';
            showToast('缓存已清除');
          } catch (error) {
            showToast('清除缓存失败');
            console.error('清除缓存失败:', error);
          } finally {
            closeToast();
          }
        })
        .catch(() => {
          // 取消操作
        });
    };

    const showLogoutConfirm = () => {
      showDialog({
        title: '退出登录',
        message: '确定要退出当前账号吗？',
        showCancelButton: true
      })
        .then(async () => {
          // 退出登录
          try {
            showLoadingToast({
              message: '退出中...',
              forbidClick: true,
            });

            await api.logout();
            // 退出后直接跳转到登录页，不需要操作localStorage
            router.push('/login');
          } catch (error) {
            showToast('退出登录失败');
            console.error('退出登录失败:', error);
          } finally {
            closeToast();
          }
        })
        .catch(() => {
          // 取消操作
        });
    };

    // 页面初始化时获取用户数据
    onMounted(() => {
      console.log('ProfileSettingsView组件已加载');
      fetchUserProfile();

      // 添加事件监听器检查
      setTimeout(() => {
        console.log('当前状态检查:');
        console.log('- 对话框显示状态:', showInput.value);
        console.log('- 性别选择器显示状态:', showGenderPicker.value);
        console.log('- 日期选择器显示状态:', showDatePicker.value);
      }, 2000);
    });

    return {
      userInfo,
      userSettings,
      cacheSize,
      genderText,
      formattedBirthday,
      minDate,
      maxDate,
      defaultDate,
      genderOptions,
      showDatePicker,
      showGenderPicker,
      showInput,
      dialogTitle,
      inputValue,
      oldPasswordValue,
      inputPlaceholder,
      currentField,
      fileInput,
      showAvatarPreview,
      previewImageUrl,
      goBack,
      maskPhone,
      openDatePicker,
      openGenderPicker,
      onPopupClosed,
      onDateConfirm,
      onGenderConfirm,
      editField,
      saveField,
      uploadAvatarAction,
      onFileChange,
      cancelAvatarUpload,
      confirmAvatarUpload,
      selectBiometricType,
      updateBiometricSettings,
      updateNotificationSettings,
      goToPrivacy,
      clearCache,
      showLogoutConfirm,
      cancelInputDialog
    };
  }
});
</script>

<style scoped>
.profile-settings-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-top: 46px;
  padding-bottom: 30px;
}

.container {
  padding: 12px;
}

.section-card {
  background-color: white;
  margin-bottom: 12px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.section-title {
  padding: 16px;
  font-size: 15px;
  font-weight: 600;
  color: #323233;
  border-bottom: 1px solid #f0f1f2;
}

.security-item {
  display: flex;
  padding: 16px;
  align-items: center;
  border-bottom: 1px solid #f0f1f2;
}

.security-item:last-child {
  border-bottom: none;
}

.security-icon {
  width: 36px;
  height: 36px;
  background-color: #ebf8ff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
  color: #3490dc;
  font-size: 16px;
}

.security-info {
  flex: 1;
}

.security-title {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 4px;
}

.security-desc {
  font-size: 12px;
  color: #969799;
}

.security-action {
  font-size: 13px;
  color: #646566;
  background-color: #f2f3f5;
  padding: 4px 12px;
  border-radius: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.security-action:hover {
  background-color: #e8e8e8;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.bio-text {
  color: #969799;
  font-size: 14px;
  text-align: right;
}

.biometric-setup {
  background-color: #f7f8fa;
  padding: 15px;
  margin: 0;
  border-top: 1px solid #f0f1f2;
}

.setup-title {
  font-size: 14px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 10px;
}

.biometric-options {
  display: flex;
  justify-content: space-around;
}

.biometric-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background-color: white;
  width: 45%;
}

.biometric-selected {
  border-color: #3490dc;
  background-color: #ebf8ff;
}

.biometric-icon {
  font-size: 24px;
  color: #3490dc;
  margin-bottom: 10px;
}

.biometric-name {
  font-size: 12px;
  color: #4a5568;
}

.logout-button {
  margin-top: 24px;
}

.version-info {
  text-align: center;
  padding: 20px 0;
  font-size: 12px;
  color: #c8c9cc;
}

.cache-size {
  color: #969799;
}

/* 头像上传和预览弹窗 */
.avatar-upload-container {
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-shrink: 0;
}

.popup-title {
  font-size: 18px;
  font-weight: 500;
}

.popup-close {
  cursor: pointer;
  color: #969799;
}

.avatar-preview-area {
  margin-bottom: 24px;
  flex-grow: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview-image {
  width: 180px;
  height: 180px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 150px;
  height: 150px;
  border: 2px dashed #dcdfe6;
  border-radius: 50%;
  color: #a8abb2;
}

.avatar-placeholder i {
    font-size: 48px;
    margin-bottom: 8px;
}

.avatar-actions {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.avatar-actions .van-button {
  flex: 1;
}

/* 覆盖Vant组件的默认样式 */
.profile-settings-page :deep(.van-cell) {
  padding: 16px;
}

.profile-settings-page :deep(.van-cell::after) {
  border-bottom-color: #f0f1f2;
}

.profile-settings-page :deep(.van-cell-group) {
  background: transparent;
}
</style>